package com.maxd.controller.userinfo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.adapter.LoginRequired;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.modules.member.entity.Member;
import com.maxd.modules.member.service.IMemberService;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.jifen.JiFenJpaRepository;
import com.maxd.respository.jifen.JiFenRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.Apple.IAppleService;
import com.maxd.service.jifen.IJiFenService;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.service.wx.AccountService;
import com.maxd.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@RestController
@Api(value = "用户信息管理", tags = {"用户信息管理"})
@RequestMapping(value = "/user")
@Slf4j
public class UserInfosController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IJiFenService jiFenService;
    @Autowired
    private JiFenJpaRepository jiFenRepository;
    @Autowired
    private JiFenRepository fenRepository;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private IMoneyDetailsService iMoneyDetailsService;
    @Autowired
    private IAppleService appleService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private IMemberService memberService;
    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(30, 100,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());



    @PostMapping("/updateUser")
    @ApiOperation("修改用户信息")
    public Result updateUser(Long userId,String nickName,String image_url,String relationId,String invitation,String phone,String gender,String age,String wxCode,String grade,String zhiRate,String feiRate){
        UserInfo userById = userRepository.getUserById(userId);
        if(StringUtils.isNotEmpty(nickName)){
            userById.setNickName(nickName);
        }
        if(StringUtils.isNotEmpty(image_url)){
            userById.setImage_url(image_url);
        }

        if(StringUtils.isNotEmpty(invitation)){
            UserInfo userByRelationId = userRepository.getUserByRelationId(invitation);
            if(userByRelationId==null){
                return ResultUtil.error(-1,"邀请码不存在！");
            }
            if(userById.getRelationId().equals(invitation)){
                return ResultUtil.error(-1,"不能输入自己的邀请码！");
            }
            userById.setInvitation(invitation);
        }
        if(StringUtils.isNotEmpty(relationId)){
            UserInfo userByRelationId = userRepository.getUserByRelationId(invitation);
            if(userByRelationId!=null && userByRelationId.getId()!=userId){
                return ResultUtil.error(-1,"邀请码已存在！");
            }
            userById.setRelationId(relationId);
        }
        if(StringUtils.isNotEmpty(phone)){
            userById.setPhone(phone);
        }
        if(StringUtils.isNotEmpty(gender)){
            userById.setGender(gender);
        }
        if(StringUtils.isNotEmpty(grade)){
            userById.setGrade(grade);
        }
        if(StringUtils.isNotEmpty(zhiRate)){
            userById.setZhiRate(zhiRate);
        }
        if(StringUtils.isNotEmpty(feiRate)){
            userById.setFeiRate(feiRate);
        }
        userJpaRepository.save(userById);
        return ResultUtil.success();
    }

    @PostMapping("/updateUserOrdersJiFen")
    @ApiOperation("修改积分")
    public Result updateUserOrdersJiFen(Long userId,String jiFen,Integer type){
        JiFen jiFens = new JiFen();
        if(type==1){
            userRepository.addOrderJifen(jiFen,userId);
            jiFens.setDes("系统增加积分："+jiFens);
        }else{
            userRepository.lessOrderJifen(jiFen,userId);
            jiFens.setDes("系统扣除积分："+jiFens);
        }
        jiFens.setCreateAt(DateUtil.createTime());
        jiFens.setContent("系统修改积分");

        jiFens.setNumber(jiFen);
        jiFens.setUserId(String.valueOf(userId));
        jiFenRepository.save(jiFens);
        return ResultUtil.success();
    }

    static boolean flag=false;

    @GetMapping("/sysnUserGradeIndex")
    @ApiOperation("同步所有用户的等级")
    public Result sysnUserGradeIndex(){
        if(flag){
            return ResultUtil.error(500,"正在同步中，请不要重复点击");
        }
        flag=true;
        final int[] page = {0};
        int limit=10;
        singleThreadPool.submit(() -> {
            while (true){
                Pageable pageable=PageRequest.of(page[0],limit);
                Page<UserInfo> page1 = userRepository.findPage(pageable);
                List<UserInfo> userInfoList = page1.getContent();
                for(UserInfo userInfo:userInfoList){
                    String invitation=userInfo.getInvitationCode();
                    String count = userRepository.getCount(invitation);
                    Member member = memberService.findMemberByPeopleNum(Integer.parseInt(count));
                    if (member != null) {
                        userInfo.setGrade(member.getRate());
                        userInfo.setZhiRate(member.getZhiRate());
                        userInfo.setFeiRate(member.getFeiRate());
                        userInfo.setGradeIndex(String.valueOf(member.getGrade()));
                        userInfo.setGradeTime(DateUtil.createTime());
                        userJpaRepository.save(userInfo);
                    }
                }
                int totalPages = page1.getTotalPages()-1;
                if(page[0] ==totalPages){
                    flag=false;
                    break;
                }
                page[0]++;
            }
        });
        return ResultUtil.success();
    }


    @RequestMapping(value = "/apple/login", method = RequestMethod.POST)
    @ApiOperation("苹果登陆获取appleUserId")
    @IgnoreSecurity
    public Result loginVerify(@RequestParam("identityToken") String identityToken) {
        try {
            log.info("[AppleController.loginVerify] [start] [identityToken is {}]", identityToken);
            return appleService.getAppleUserInfo(identityToken);
        } catch (Exception e) {
            log.error("[AppleController.loginVerify] [error] [identityToken is {}]", identityToken, e);
            return ResultUtil.error(10001,"参数有误！");
        }
    }


    @GetMapping("/synchronizationUser")
    @ApiOperation("同步客户邀请码")
    @IgnoreSecurity
    @ResponseBody
    public Result synchronizationUser(){
        List<UserInfo> userInfos = userRepository.selectUserList();
        for(UserInfo userInfo:userInfos){
            if(StringUtils.isBlank(userInfo.getInvitationCode())){
                userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo.getId()));
                userService.saveBody(userInfo);
            }
        }
        return ResultUtil.success();
    }


    @PostMapping("/updateNickName")
    @ApiOperation("修改用户名")
    @ResponseBody
    public Result updateNickName(Long userId,String nickName){
        Integer integer = userRepository.updateNickName(nickName, userId);
        if(integer>0){
            return ResultUtil.success();
        }
        return ResultUtil.error(-100,"修改失败，刷新页面后重试！");
    }

    @PostMapping("/updateImgUrl")
    @ApiOperation("修改头像")
    @ResponseBody
    public Result updateImgUrl(Long userId,String imgUrl){
        Integer integer = userRepository.updateImgUrl(imgUrl, userId);
        if(integer>0){
            return ResultUtil.success();
        }
        return ResultUtil.error(-100,"修改失败，刷新页面后重试！");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation("用户端和管理平台获取用户详情")
    @ResponseBody
    @IgnoreSecurity
    public Result getUserInfoById(HttpServletRequest request,@PathVariable Integer id) {
        Object userId = request.getAttribute("userId");
        if(userId!=null){
            id=Integer.parseInt(String.valueOf(userId));
        }else{
            Object adminId = request.getAttribute("adminId");
            if(adminId==null){
                return ResultUtil.success();
            }
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        //每日登陆签到
        Long countByTime = fenRepository.countJiFenLogin(sdf1.format(new Date()), String.valueOf(id));//统计积分数量
        if (countByTime == 0) {
            UserInfo userInfo = userJpaRepository.findById(Long.valueOf(id)).orElse(null);
            if (userInfo != null && userInfo.getRelationId() != null) {
                CommonInfo one = commonRepository.findOne(78);
                double v = Double.parseDouble(one.getValue());
                double orderJifen = Float.parseFloat(userInfo.getOrderJifen());
                userInfo.setOrderJifen(String.valueOf(orderJifen + v));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date now = new Date();
                JiFen jiFen = new JiFen();
                jiFen.setCreateAt(sdf.format(now));
                jiFen.setContent("每日登录");
                jiFen.setDes(sdf1.format(new Date()) + "登录+" + one.getValue() + "积分");
                jiFen.setNumber(one.getValue());
                jiFen.setUserId(String.valueOf(id));
                userJpaRepository.save(userInfo);
                jiFenRepository.save(jiFen);
            }
        }
        return iUserService.findOne(Long.valueOf(id));
    }

    @RequestMapping(value = "/getUserJifenList/{userId}", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端获取用户积分")
    public Result getUserJifenList(@PathVariable Long userId) {
        return jiFenService.findList(userId);
    }

    @RequestMapping(value = "/getUserJifenList/{userId}/{page}/{size}", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端获取用户积分分页")
    public Result getUserJifenList1(HttpServletRequest request,@PathVariable Long userId,@PathVariable Integer page,@PathVariable Integer size) {
        Object userIds = request.getAttribute("userId");
        if(userIds!=null){
            userId=Long.parseLong(String.valueOf(userIds));
        }else{
            Object adminId = request.getAttribute("adminId");
            if(adminId==null){
                return ResultUtil.success();
            }
        }
        return jiFenService.findList1(userId,page, size);
    }

    @RequestMapping(value = "/cashMoney/{userId}", method = RequestMethod.GET)
    @ResponseBody

    @ApiOperation("用户端积分兑换钱币")
    public Result moneyCash(@PathVariable Long userId, @RequestParam String money) {
        UserInfo one = userJpaRepository.getOne(userId);
        DecimalFormat df = new DecimalFormat("#########.##");
        String orderJifen = one.getOrderJifen();
        double m = Float.parseFloat(money);
        double i = Float.parseFloat(orderJifen);
        if(m>i){
            return ResultUtil.error(-100,"积分数量不足，请输入正确的积分数量");
        }
        //剩余积分
        double a = i - m;
        //计算金额
        double f1 = Float.parseFloat(df.format(m * 0.001));
        String ji = df.format(f1);
        String orderji = df.format(a);
        //保存可提现金额
        userRepository.updateJiFenAdd(ji,one.getId());
        //保存剩余积分
        userRepository.updateOrderJifen(orderji,one.getId());
       /* one.setJifen(f);
        //保存剩余积分
        one.setOrderJifen(df.format(a));*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        JiFen jiFen = new JiFen();
        jiFen.setCreateAt(sdf.format(now));
        jiFen.setContent("积分兑换");
        jiFen.setDes("积分兑换-" + money);
        jiFen.setNumber(money);
        jiFen.setUserId(String.valueOf(userId));
//        userJpaRepository.save(one);
        iMoneyDetailsService.saveBody(one.getId(),1,2,"积分兑换","积分兑换金额，消耗积分："+m+",兑换金额："+ji,Double.parseDouble(ji));

        jiFenRepository.save(jiFen);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/selectUserDetails", method = RequestMethod.GET)
    @ApiOperation("获取用户钱包明细")
    @ResponseBody
    public Result selectUserDetails(HttpServletRequest request,int page,int size,Long userId) {
        Object userIds = request.getAttribute("userId");
        if(userIds!=null){
            userId=Long.parseLong(String.valueOf(userIds));
        }else{
            Object adminId = request.getAttribute("adminId");
            if(adminId==null){
                return ResultUtil.success();
            }
        }
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(iMoneyDetailsService.selectMoneyDetailsByUserId(pageable,userId));
    }

    @GetMapping("/userNumber")
    @IgnoreSecurity
    public Result userNumber() {
        List<UserInfo> all = userJpaRepository.findAll();
        for (UserInfo u : all) {
            if (u.getRelationId() != null) {
                u.setIsRelation(1);
                userJpaRepository.save(u);
            }
        }
        return ResultUtil.success();
    }

    /**
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteByUserId", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ResponseBody
    public Result deleteById(Long userId) {
        //删除用户
        userJpaRepository.deleteById(userId);
        //删除用户关联积分表信息
        fenRepository.deleteJiFenByUserId(userId);
        return ResultUtil.success();
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/notification/{id}", method = RequestMethod.POST)
    @ApiOperation("管理平台消息推送")
    @ResponseBody
    public Result updateIsOut(@PathVariable Long id) {
        CommonInfo url = commonRepository.findOne(19);
        UserInfo one = userJpaRepository.findById(id).orElse(null);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        assert one != null;
        totalSuccess(one.getOpenId(), one.getNickName(), sdf1.format(new Date()), one.getJifen(), one.getJifen(), url.getValue());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation("用户端 APP中手机号密码注册")
    @ResponseBody
    public Result registerUser(@RequestBody UserInfo userInfo) {
        if (userInfo.getPhone().isEmpty()) {
            return ResultUtil.error(ExceptionEnum.USER_PHONE_ERROR);
        } else {
            UserInfo userByPhone = iUserService.getUserByPhone(userInfo.getPhone());
            if (userByPhone == null) {
                iUserService.saveBody(userInfo);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(ExceptionEnum.USER_IS_EXITS);
            }
        }

    }

    @RequestMapping(value = "/page/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理平台用户列表")
    @ResponseBody
    public Result getBodyPage(@PathVariable Integer page, @PathVariable int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(userJpaRepository.findAll(pageable));
    }


    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    @ApiOperation("管理平台积分零钱用户列表")
    @ResponseBody
    public Result getBodyPage(@RequestParam String phone, @RequestParam Integer page, @RequestParam int size,@RequestParam int type,String gradeIndex) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if(type==1){
            if(StringUtils.isNotEmpty(phone)){
                return ResultUtil.success(userRepository.findOrderJifenByPhone(phone,pageable,gradeIndex));
            }
            return ResultUtil.success(userRepository.findOrderJifenList(pageable,gradeIndex));
        }
        if(StringUtils.isNotEmpty(phone)){
            return ResultUtil.success(userRepository.findJifenByPhone(phone,pageable,gradeIndex));
        }
        return ResultUtil.success(userRepository.findJifenByPhoneList(pageable,gradeIndex));
    }

    @RequestMapping(value = "/getCountNumber", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台累计总用户数")
    public Result getCountNumber() {
        return ResultUtil.success(userRepository.getCountNumber());
    }

    @RequestMapping(value = "/getCountNumber/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台会员用户和非会员用户总数")
    public Result getCountNumberMember(@PathVariable int id) {
        return ResultUtil.success(userRepository.getCountNumberMember(id));
    }

    @RequestMapping(value = "/findAllByRelationIdNotNull", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台统计淘宝授权用户")
    public Result findAllByRelationIdNotNull() {
        return ResultUtil.success(userRepository.selectUserInfoByNotRelationId());
    }

    @RequestMapping(value = "/findAllByJifenNotNullOrderByIdDesc", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台获取普通用户")
    public Result findAllByJifenNotNullOrderByIdDesc() {
        return ResultUtil.success(userRepository.selectUserInfoByRelationIdIsNull());
    }

    @RequestMapping(value = "/findAllByOrderJifenNotNullOrderByIdDesc", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台获取已有积分用户")
    public Result findAllByOrderJifenNotNullOrderByIdDesc() {
        return ResultUtil.success(userRepository.selectUserInfoByNotJifen());
    }

    @RequestMapping(value = "/getCountNumberByTime/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台每日会员用户和非会员用户总数")
    public Result getCountNumberByTime(@PathVariable int id, @RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTime(time, id));
    }

    @IgnoreSecurity
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation("用户端APP 中登录")
    @ResponseBody
    public Result login(@RequestBody LoginInfo loginInfo) {
        return iUserService.Login(loginInfo);
    }

    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@RequestBody LoginInfo loginInfo) {
        return iUserService.updatePwd(loginInfo.getOld(), loginInfo.getPwd(), loginInfo.getUserId());
    }



    @IgnoreSecurity
    @ApiOperation("用户端忘记密码")
    @RequestMapping(value = "/forgetPwd", method = RequestMethod.POST)
    @ResponseBody
    public Result forgetPwd(@RequestBody LoginInfo loginInfo) {
        return iUserService.forgetPwd(loginInfo.getPwd(), loginInfo.getPhone(), loginInfo.getMsg());
    }

    @IgnoreSecurity
    @ApiOperation("用户端openid登录呢")
    @RequestMapping(value = "/openid/login", method = RequestMethod.GET)
    @ResponseBody
    public Result loginByOpenId(@RequestParam String openid, @RequestParam String relation) {
        return iUserService.loginByOpenId(openid, relation);

    }

    @RequestMapping(value = "/mp/update", method = RequestMethod.POST)
    @ResponseBody
    @IgnoreSecurity
    @ApiOperation("用户端小程序更新用户信息注册")
    public Result mpUpdateUser(@RequestBody LoginInfo loginInfo) {
        return iUserService.mpUpdateUser(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/openid/{openid}/{relation}", method = RequestMethod.GET)
    @ApiOperation("用户端会员登录 未使用 在关注公众号中使用")
    @ResponseBody
    public Result loginByOpenIdWithRelation(@PathVariable String openid, @PathVariable String relation) {
        return iUserService.loginByOpenIdWithRelation(openid, relation);
    }


    @IgnoreSecurity
    @ApiOperation("用户端发送验证码")
    @RequestMapping(value = "/sendMsg/{phone}/{state}", method = RequestMethod.GET)
    @ResponseBody
    public Result sendMsg(@PathVariable String phone, @PathVariable String state) {
        return iUserService.sendMsg(phone, state);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/bindOpenid", method = RequestMethod.POST)
    @ApiOperation("用户端绑定openid")
    @ResponseBody
    public Result bindOpenid(@RequestBody LoginInfo loginInfo) {
        if (StringUtils.isNotEmpty(loginInfo.getOpenid())) {
            return iUserService.bindOpenid(loginInfo);
        } else {
            return iUserService.loginCode(loginInfo);
        }
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginTaoBao", method = RequestMethod.POST)
    @ApiOperation("用户端淘宝登录绑定手机号")
    @ResponseBody
    public Result loginTaoBao(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginTaoBao(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginWeiXinApp", method = RequestMethod.POST)
    @ApiOperation("用户端微信登录绑定手机号")
    @ResponseBody
    public Result loginWeiXinApp(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginWeiXinApp(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/bindTaoBao", method = RequestMethod.POST)
    @ApiOperation("用户端手机号账号绑定淘宝")
    @ResponseBody
    public Result bindTaoBao(@RequestBody LoginInfo loginInfo) {
        return iUserService.bindTaoBao(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginApp", method = RequestMethod.POST)
    @ApiOperation("用户端使用微信登录")
    @ResponseBody
    public Result loginApp(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginApp(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginTb", method = RequestMethod.POST)
    @ApiOperation("用户端使用淘宝登录")
    @ResponseBody
    public Result loginTb(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginTb(loginInfo);
    }

    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@RequestParam String phone, @RequestParam String msg, @RequestParam String userId) {
        return iUserService.updatePhone(phone, msg, userId);
    }

    @RequestMapping(value = "/updateClientId", method = RequestMethod.POST)
    @ApiOperation("用户端绑定消息推送clientId")
    @IgnoreSecurity
    @ResponseBody
    public Result updateClientId(@RequestParam String clientId, @RequestParam String userId,Integer sysPhone) {
        userService.updateUserClientIdIsNull(clientId);
        UserInfo userInfo = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        System.out.println(clientId);
        if (userInfo != null) {
            userInfo.setSysPhone(sysPhone);
            userInfo.setClientid(clientId);
            return ResultUtil.success(userJpaRepository.save(userInfo));
        }
        return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
    }

    @RequestMapping(value = "/bindPhone", method = RequestMethod.POST)
    @ApiOperation("用户端绑定手机号")
    @ResponseBody
    public Result bindPhone(@RequestParam String phone, @RequestParam String msg, @RequestParam String userId) {
        return iUserService.bindPhone(userId, phone, msg);
    }

    @RequestMapping(value = "/updateInvitation/{userId}", method = RequestMethod.POST)
    @ApiOperation("管理平台更新用户授权状态")
    @ResponseBody
    public Result updateInvitation(@PathVariable Long userId) {
        UserInfo one = userJpaRepository.findById(userId).orElse(null);
        assert one != null;
        if (one.getIsInvitation() == 0) {
            one.setIsInvitation(1);
        } else {
            one.setIsInvitation(0);
        }
        return ResultUtil.success(userJpaRepository.save(one));
    }

    @RequestMapping(value = "/updateState/{userId}", method = RequestMethod.POST)
    @ApiOperation("管理平台更新用户的账号状态")
    @ResponseBody
    public Result updateState(@PathVariable Long userId) {
        UserInfo one = userJpaRepository.findById(userId).orElse(null);
        assert one != null;
        if (one.getState().equals("true")) {
            one.setState("false");
        } else {
            one.setState("true");
        }
        return ResultUtil.success(userJpaRepository.save(one));
    }
    @RequestMapping(value = "/updateIsTuan/{userId}", method = RequestMethod.POST)
    @ApiOperation("管理平台更新用户的团长状态")
    @ResponseBody
    public Result updateIsTuan(@PathVariable Long userId) {
        UserInfo one = userJpaRepository.findById(userId).orElse(null);
        assert one != null;
        if (1==one.getIsTuan()) {
            one.setIsTuan(-1);
        } else {
            one.setIsTuan(1);
        }
        return ResultUtil.success(userJpaRepository.save(one));
    }
    @RequestMapping(value = "/updateIsTopTuan/{userId}", method = RequestMethod.POST)
    @ApiOperation("管理平台更新用户的顶级团长状态")
    @ResponseBody
    public Result updateIsTopTuan(@PathVariable Long userId) {
        UserInfo one = userJpaRepository.findById(userId).orElse(null);
        assert one != null;
        if (1==one.getIsTopTuan()) {
            one.setIsTopTuan(-1);
        } else {
            one.setIsTopTuan(1);
            one.setIsTuan(1);
            //移除顶级团长的上级
            one.setInvitation("");
        }
        return ResultUtil.success(userJpaRepository.save(one));
    }


    @RequestMapping(value = "/updateGrades", method = RequestMethod.GET)
    @ApiOperation("管理平台修改用户等级")
    @ResponseBody
    public Result updateGrade(@RequestParam String userId, @RequestParam String grade) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        assert one != null;
        one.setGrade(grade);
        one.setId(one.getId());
        return ResultUtil.success(userJpaRepository.save(one));
    }

    @RequestMapping(value = "/updateName", method = RequestMethod.GET)
    @ApiOperation("管理平台修改备注")
    @ResponseBody
    public Result updateName(@RequestParam String userId, @RequestParam String name) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        assert one != null;
        one.setName(name);
        one.setId(one.getId());
        return ResultUtil.success(userJpaRepository.save(one));
    }

    @RequestMapping(value = "/bind/relationId/{relationId}/{userid}", method = RequestMethod.GET)
    @ApiOperation("用户端绑定渠道")
    @ResponseBody
    public Result bindRelationId(@PathVariable String relationId, @PathVariable String userid) {
        return iUserService.bindRelationId(userid, relationId);
    }

    @RequestMapping(value = "/bind/relationCode/{relationId}/{userid}/{code}", method = RequestMethod.GET)
    @ApiOperation("用户端获取渠道")
    @ResponseBody
    public Result bindRelationIdCode(@PathVariable String relationId, @PathVariable String userid, @PathVariable String code) {
        return iUserService.bindRelationIdCode(userid, relationId, code);
    }

    @RequestMapping(value = "/bind/openid/{openid}/{userid}", method = RequestMethod.GET)
    @ApiOperation("用户端绑定opneid")
    @ResponseBody
    public Result bindOpenId(@PathVariable String openid, @PathVariable String userid) {
        return iUserService.bindOpenId(userid, openid);
    }

    @RequestMapping(value = "/userinfo/{userId}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端获取用户信息")
    @LoginRequired
    public Result getUserInfo(@PathVariable String userId) {
        return iUserService.findOne(Long.valueOf(userId));
    }

    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    @ApiOperation("管理平台获取用户列表")
    @ResponseBody
    public Result getUserList(@RequestParam String phone, @RequestParam Integer page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if (!phone.isEmpty() && !phone.equals("undefined")) {
            return iUserService.find(phone, pageable);
        } else {
            return iUserService.findList(pageable);
        }
    }

    @RequestMapping(value = "/getUsersByInvitation", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户列表")
    @ResponseBody
    public Result getUsersByInvitation(@RequestParam String invitation, @RequestParam Integer page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return iUserService.getUsersByInvitation(invitation, pageable);
    }

    @RequestMapping(value = "/getInvitation", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getInvitation(@RequestParam String invitation) {
        return iUserService.getInvitation(invitation);
    }

    @RequestMapping(value = "/getInvitations/{invitation}/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getInvitations(@PathVariable("invitation") String invitation,@PathVariable("page") int page,@PathVariable("size") int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(userRepository.getInvitations(invitation,pageable));
    }

    @RequestMapping(value = "/getInvitations/{invitation}/{page}/{size}/{type}", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getInvitations(@PathVariable("invitation") String invitation,@PathVariable("page") int page,@PathVariable("size") int size,@PathVariable("type") int type) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if(type==1){
            return ResultUtil.success(userRepository.getInvitations(invitation,pageable));
        }else{
            return ResultUtil.success(userRepository.getInvitationss(invitation,pageable));
        }
    }

    @RequestMapping(value = "/getCount", method = RequestMethod.GET)
    @ApiOperation("管理平台和用户获取邀请用户用户列表")
    @ResponseBody
    public Result getCount(@RequestParam String invitation) {
        return ResultUtil.success(userRepository.getCounts(invitation));
    }

    @RequestMapping(value = "/getCash", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getCash(@RequestParam String invitation) {
        return iUserService.getCash(invitation);
    }

    @RequestMapping(value = "/relationId", method = RequestMethod.GET)
    @ApiOperation("用户端通过渠道id获取用户信息")
    @ResponseBody
    public Result getUserBuyRelation(@RequestParam String relationId) {
        return ResultUtil.success(userRepository.getUserByRelationId(relationId));
    }

    @RequestMapping(value = "/checkRelationInvitations", method = RequestMethod.GET)
    @ResponseBody
    @IgnoreSecurity
    public Result checkRelationInvitations(@RequestParam String invitation, String userOpenid, String phone) {
        return ResultUtil.success(iUserService.checkRelationInvitations(invitation, phone));
    }

    @RequestMapping(value = "/userList/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理平台多条件查询语句")
    @ResponseBody
    public Result userList(@PathVariable int page, @PathVariable int size, @RequestParam String phone, @RequestParam String platform, @RequestParam int isRelation, @RequestParam int isTuan, @RequestParam(required = false, defaultValue = "-1") String nickName,String startTime,String endTime,String gradeIndex) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        // 构造自定义查询条件
        Specification<UserInfo> queryCondition = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!platform.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("platform"), platform));
                }
                if (!phone.equals("-1")) {
                    predicateList.add(criteriaBuilder.equal(root.get("phone"), phone));
                }
                if (!nickName.equals("-1")) {
                    predicateList.add(criteriaBuilder.like(root.get("nickName"), "%" + nickName + "%"));
                }
                if (isRelation != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isRelation"), isRelation));
                }
                if (isTuan != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isTuan"), isTuan));
                }
                if (StringUtils.isNotEmpty(gradeIndex)) {
                    predicateList.add(criteriaBuilder.equal(root.get("gradeIndex"), gradeIndex));
                }
                if (StringUtils.isNotEmpty(startTime)) {
                    predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createAt"), startTime));
                }
                if (StringUtils.isNotEmpty(endTime)) {
                    predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createAt"), endTime));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        Page<UserInfo> all = userJpaRepository.findAll(queryCondition, pageable);
        List<UserInfo> content = all.getContent();
        for(UserInfo user:content){
            UserMoney userMoney = userMoneyService.selectByUserId(user.getId());
            BigDecimal add = new BigDecimal(user.getJifen()).add(BigDecimal.valueOf(userMoney.getMoney()));
            user.setJifen(String.valueOf(add));
        }
        return ResultUtil.success(all);
    }

    @RequestMapping(value = "/userListExcel", method = RequestMethod.GET)
    @ApiOperation("导出管理平台多条件查询语句")
    @IgnoreSecurity
    public void userListExcel(@RequestParam String phone, @RequestParam String platform, @RequestParam int isRelation, @RequestParam int isTuan, @RequestParam(required = false, defaultValue = "-1") String nickName,String startTime,String endTime,String gradeIndex, HttpServletResponse response) throws Exception {
        // 构造自定义查询条件
        Specification<UserInfo> queryCondition = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!platform.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("platform"), platform));
                }
                if (!phone.equals("-1")) {
                    predicateList.add(criteriaBuilder.equal(root.get("phone"), phone));
                }
                if (!nickName.equals("-1")) {
                    predicateList.add(criteriaBuilder.like(root.get("nickName"), "%" + nickName + "%"));
                }
                if (isRelation != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isRelation"), isRelation));
                }
                if (isTuan != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isTuan"), isTuan));
                }
                if (StringUtils.isNotEmpty(gradeIndex)) {
                    predicateList.add(criteriaBuilder.equal(root.get("gradeIndex"), gradeIndex));
                }
                if (StringUtils.isNotEmpty(startTime)) {
                    predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createAt"), startTime));
                }
                if (StringUtils.isNotEmpty(endTime)) {
                    predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createAt"), endTime));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<UserInfo> all = userJpaRepository.findAll(queryCondition);
        for(UserInfo user:all){
            UserMoney userMoney = userMoneyService.selectByUserId(user.getId());
            BigDecimal add = new BigDecimal(user.getJifen()).add(BigDecimal.valueOf(userMoney.getMoney()));
            user.setJifen(String.valueOf(add));
        }
        ExcelData data = new ExcelData();
        if(isRelation==-1){
            if(isTuan==1){
                data.setName("团长用户");
            }else{
                data.setName("全部用户");
            }
        }else if(isRelation==1){
            data.setName("会员用户");
        }else if(isRelation==0){
            data.setName("普通用户");
        }else{
            data.setName("未命名");
        }

        List<String> titles = new ArrayList();
        titles.add("编号");titles.add("昵称");titles.add("手机号");titles.add("创建时间");
        titles.add("性别");titles.add("邀请人");titles.add("等级");titles.add("支付宝");
        titles.add("余额");titles.add("积分");titles.add("备注");titles.add("来源");
        titles.add("状态");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        DecimalFormat df = new DecimalFormat("#########.##");
        for(UserInfo userInfo:all){
            List<Object> row = new ArrayList();
            row.add(userInfo.getId());row.add(userInfo.getNickName());row.add(userInfo.getPhone());row.add(userInfo.getCreateAt());
            String gender = userInfo.getGender();
            if(StringUtils.isBlank(gender)||"0".equals(gender)  || "null".equals(gender)){
                row.add("未知");
            }else if("1".equals(gender)){
                row.add("男");
            }else{
                row.add("女");
            }
            row.add(userInfo.getInvitation());row.add(userInfo.getGrade());row.add(userInfo.getZhifubao());
            String jifen = userInfo.getJifen();
            if(StringUtils.isBlank(jifen)||"0".equals(jifen) || "null".equals(jifen)){
                row.add(0);
            }else{
                row.add(df.format(Float.parseFloat(jifen)));
            }
            String orderJifen = userInfo.getOrderJifen();
            if(StringUtils.isBlank(orderJifen)||"0".equals(orderJifen) || "null".equals(orderJifen)){
                row.add(0);
            }else{
                row.add(df.format(Float.parseFloat(orderJifen)));
            }
            row.add(userInfo.getName());
            String platform1 = userInfo.getPlatform();
            if("wap".equals(platform1)){
                row.add("网站");
            }else if("app".equals(platform1)){
                row.add("app");
            }else if("weixin".equals(platform1)){
                row.add("微信公众号");
            }else if("mp".equals(platform1)){
                row.add("微信小程序");
            }else{
                row.add("未知");
            }
            if("true".equals(userInfo.getState())){
                row.add("正常");
            }else{
                row.add("禁用");
            }
            rows.add(row);
        }
        data.setRows(rows);
        ExportExcelUtils.exportExcel(response,"用户列表.xlsx",data);
    }




    /**
     * 获取用户邀请人
     *
     * @return
     */
    @RequestMapping(value = "/team/users/{relation}", method = RequestMethod.GET)
    @ApiOperation("获取用户邀请人")
    @ResponseBody
    public Result getTeamTotal(@PathVariable String relation) {
        List<invitationTotal> list = new ArrayList<>();
        List<Long> usersByInvitations = userRepository.getUsersByInvitations(relation);
        List<UserInfo> allUser = userJpaRepository.findAll();
        for (Long usersByInvitation : usersByInvitations) {
            UserInfo byId = new UserInfo();
            for (UserInfo u : allUser) {
                if (usersByInvitation == u.getId()){
                    byId = u;
                }
            }
            //UserInfo byId = userJpaRepository.findById(usersByInvitation).orElse(null);
            invitationTotal invitationTotal = new invitationTotal();
            assert byId != null;
            invitationTotal.setGrade(byId.getRelationId());
            invitationTotal.setTime(byId.getCreateAt());
            if (byId.getNickName() != null) {
                invitationTotal.setUserName(byId.getNickName());
            } else {
                invitationTotal.setUserName(byId.getPhone());
            }
            if (StringUtils.isNotBlank(byId.getRelationId())) {
                String s = orderRepository.countByRelationMoney(Long.valueOf(byId.getRelationId()));
                if (StringUtils.isNotBlank(s)) {
                    invitationTotal.setMoney(Math.round(Float.parseFloat(s)));
                } else {
                    invitationTotal.setMoney(0);
                }
            } else {
                invitationTotal.setMoney(0);
            }
            if (invitationTotal.getUserName() == null) {
                invitationTotal.setUserName("用户："+byId.getId());
            }
            list.add(invitationTotal);
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    /**
     * 获取用户邀请人
     *
     * @return
     */
    @RequestMapping(value = "/team/users/{relation}/{type}/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("获取用户邀请人")
    @ResponseBody
    public Result getTeamTotal(@PathVariable("relation") String relation,@PathVariable("type") Integer type,@PathVariable("page") Integer page,@PathVariable("size") Integer size) {
        Page<Map<String, Object>> usersByInvitations1=null;
        Pageable pageable = PageRequest.of(page, size);
        if(type==1){
            usersByInvitations1 = userRepository.getUsersByInvitations1(pageable, relation);//456
        }else{
            usersByInvitations1 = userRepository.getUsersByInvitationss(pageable,relation);//789
        }
        return ResultUtil.success(usersByInvitations1);
    }

    private void totalSuccess(String openId, String name, String date, String money, String totalMoney, String url) {
        UserInfo userByWxId = userRepository.getUserByWxId(openId);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(4));
        messageInfo.setContent(name + " 您好！您上月【确认收货订单】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现");
        messageInfo.setTitle("本月结算通知");
        messageInfo.setUserName(userByWxId.getNickName());
        messageInfo.setUserId(String.valueOf(userByWxId.getId()));
        iMessageService.saveBody(messageInfo);
        if (userByWxId.getClientid() != null) {
            userService.pushToSingle("本月结算通知", name + " 您好！您上月【确认收货订单】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现", userByWxId.getClientid());
        }
        CommonInfo three = commonRepository.findOne(37);
        String apkey = Config.JieSuanNotification;
        if (three != null) {
            apkey = three.getValue();
        }
        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
        data.put("thing1", new TemplateMessageItem("您好！您上月【确认收货订单】已经结算", "#d71345"));
        data.put("amount4", new TemplateMessageItem(money + " 元", "#d71345"));
        accountService.sendWxMessage(apkey, data, openId, url);
    }



    /**
     * 分页查询系统用户 / 根据ID查询用户详情
     * @param phone
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/queryHelpTaskUserList", method = RequestMethod.POST)
    @ApiOperation("管理平台用户列表")
    @IgnoreSecurity
    public Result queryHelpTaskUserList(@RequestParam String phone,@RequestParam int page, @RequestParam int size) {
        Pageable pageable = PageRequest.of(page, size);
        if("".equals(phone)){
            return iUserService.findListByTwo(pageable);
        }else{
            return userService.findByPhoneAndSysUser(phone,pageable);
        }
    }

    /**
     * 查询用户金额
     */
    @RequestMapping(value = "/queryHelpTaskUserAmount", method = RequestMethod.POST)
    @ApiOperation("查询用户金额")
    public Result queryHelpTaskUserAmount(@RequestParam Long userId){
        UserMoney userMoney = userMoneyService.selectByUserId(userId);
        if(userMoney==null){
            return ResultUtil.error(601,"用户id不存在");
        }
        return ResultUtil.success(userMoney);
    }

    /**
     * 充值不可用金额
     */
    @RequestMapping(value = "/addHelpTaskUserAmount", method = RequestMethod.POST)
    @ApiOperation("充值不可用金额")
    public Result queryHelpTaskUserAmount(@RequestParam Long userId,@RequestParam String amount){
        UserMoney userMoney = userMoneyService.selectByUserId(userId);
        userMoneyService.updateMoneyById(userId,Double.parseDouble(amount));
        return ResultUtil.success();
    }


    /**
     * 充值可用金额
     */
    @RequestMapping(value = "/addHelpTaskUserMoney", method = RequestMethod.POST)
    @ApiOperation("充值可用金额")
    public Result addHelpTaskUserMoney(@RequestParam Long userId,@RequestParam String amount){
        userMoneyService.updateMoney(1,userId,Double.parseDouble(amount));
        return ResultUtil.success();
    }


    /**
     * 添加用户
     */
    @RequestMapping(value = "/addHelpTaskUser", method = RequestMethod.POST)
    @ApiOperation("新增")
    //@IgnoreSecurity
    public Result addHelpTaskUser(@RequestBody UserInfo userInfo) {
        UserInfo helpTaskUser = new UserInfo();
        if(userInfo==null){
            return ResultUtil.error(601,"新增失败,请稍后再试");
        }
        if (userInfo.getPhone().isEmpty()) {
            return ResultUtil.error(601,"手机号不能为空！");
        }

        String invitationCode = userInfo.getInvitationCode();
        if(invitationCode==null){
            return ResultUtil.error(601,"邀请码不能为空!");
        }

        /**手机号是否被注册*/
        UserInfo userByPhone = userService.getUserByPhone(userInfo.getPhone().trim());
        if(userByPhone!=null){
            return ResultUtil.error(601,"手机号已经被注册了！");
        }


        try {
            //手机号
            helpTaskUser.setPhone(userInfo.getPhone().trim());
            //系统用户
            helpTaskUser.setIsSysUser("2");
            //
            helpTaskUser.setJifen("0");
            //密码加密
            helpTaskUser.setPwd(DigestUtils.sha256Hex(userInfo.getPwd()));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //创建时间
            helpTaskUser.setCreateAt(simpleDateFormat.format(new java.util.Date()));
            helpTaskUser.setNickName(userInfo.getNickName());
            helpTaskUser.setImage_url(userInfo.getImage_url());


            //判断是否是系统邀请码 验证码
            CommonInfo one = commonRepository.findOne(4);
            if(invitationCode.equals(one.getValue())){
                helpTaskUser.setInvitation(invitationCode);
                helpTaskUser.setInvitationCode(CardNoUtils.generateShortUuidTwo());
                userService.saveBody(helpTaskUser);
                addUserMoney(userInfo.getPhone().trim());
            }else{
                //如果是其他用户邀请码
                UserInfo userByInvitationCode = userRepository.getUserByInvitationCode(invitationCode);
                if(userByInvitationCode==null){
                    return ResultUtil.error(601,"邀请码不存在!");
                }else{
                    helpTaskUser.setInvitation(userByInvitationCode.getInvitationCode());
                    userService.saveBody(helpTaskUser);
                    userService.setInvitationCode(helpTaskUser);
                    addUserMoney(userInfo.getPhone().trim());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(602,"新增失败,请稍后再试或联系管理员");
        }

        return ResultUtil.success("新增成功");
    }

    private void addUserMoney(String phone) {
        UserInfo userByPhone1 = userService.getUserByPhone(phone);
        UserMoney userMoney12 = new UserMoney();
        userMoney12.setCannotMoney(0.00);
        userMoney12.setMoney(0.0);
        userMoney12.setUserId(userByPhone1.getId());
        userMoneyService.save(userMoney12);
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/updatePddChoiceProd", method = RequestMethod.POST)
    @ApiOperation("根据id修改")
    //@IgnoreSecurity
    public Result updateHelpTaskUser(@RequestBody UserInfo userInfo) {
        UserInfo userInfo1 = userJpaRepository.findById(userInfo.getId()).orElse(null);
        if(userInfo1==null){
            return ResultUtil.error(601,"修改的用户不存在，请刷新后重试！");
        }
        if (userInfo.getPhone().isEmpty()) {
            return ResultUtil.error(601,"手机号不能为空");
        }
        if(StringUtils.isNotEmpty(userInfo.getPwd())){
            userInfo.setPwd(DigestUtils.sha256Hex(userInfo.getPwd()));
        }else{
            userInfo.setPwd(userInfo1.getPwd());
        }
        try {
            userService.updateHelpTaskUserById(userInfo);
        }catch (Exception e){
            return ResultUtil.error(602,"修改失败,请稍后再试或联系管理员");
        }

        return ResultUtil.success("修改成功");
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    //@IgnoreSecurity
    public Result deleteByIdBy(@RequestParam Long id) {
        userService.deleteById(id);
        return ResultUtil.success();
    }


    /**
     * 根据ids批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteByIdList", method = RequestMethod.POST)
    @ApiOperation("删除多个用户")
    //@IgnoreSecurity
    public Result deleteByIdList(@RequestParam String ids) {
        userService.deleteByIdList(ids);
        return ResultUtil.success();
    }


    @GetMapping("/getPhoneByOpenId")
    @ApiOperation("根据微信公众号OpenId判断用户是否绑定手机号")
    @IgnoreSecurity
    public Result updateInvitationCode(String openId){
        UserInfo userByWxId = userRepository.getUserByWxId(openId);
        if(userByWxId!=null){
            if(StringUtils.isEmpty(userByWxId.getPhone())){
                return ResultUtil.error(-2,"未绑定手机号！");
            }else{
                return ResultUtil.success(userByWxId);
            }
        }
        return ResultUtil.error(-1,"账号不存在！");

    }

    @GetMapping("/updateInvitationCode")
    @IgnoreSecurity
    public Result updateInvitationCode(){
        return userService.updateInvitationCode();
    }

    @PostMapping("/updateUserWxImg")
    public Result updateUserWxImg(Long userId,String wxImg){
        UserInfo userById = userRepository.getUserById(userId);
        userById.setWxImg(wxImg);
        userJpaRepository.save(userById);
        return ResultUtil.success();
    }

    @ApiOperation("二维码生成")
    @GetMapping(value = "/getImg")
    @IgnoreSecurity
    public Result getImg(@RequestParam String page,@RequestParam(required = false) String scene, @RequestParam String width,HttpServletResponse response) {
        return iUserService.getImg(page, scene, width, response);
    }


}
